<script setup>

import {Refresh, Search} from "@element-plus/icons-vue";
import {onMounted, ref} from "vue";
import axios from "axios";

const formLabelWidth = ref('140px');
let tableData=ref([]);
let dialogFormVisibleAdd=ref(false);
let str1=ref("");
let dialogFormVisibleEdit=ref(false);//修改弹窗
// 存储用户选择的文件
const selectedFile = ref(null);
// 存储上传成功后的 URL
const uploadedUrl = ref('');
// 存储错误信息
const errorMessage = ref('');
const deleteIndex=ref(null);
const EditIndex=ref(null);
const dialogFormVisibleDel=ref(false);
// 存储选择的id
let arrayData=ref([]);
let dialogFormVisibleDel1=ref(false);
// 搜索内容
let title=ref("");
let searchContent=ref("");
// 分页
let total=ref(1000);
let  currentPage=ref(1);
let pageSize=ref(5);

// 分页
const handleCurrentChange=(pageNum)=>{
  currentPage.value=pageNum;
  suaxin();

}








let form=ref({

  knowledgeId:null,
  title:"",
  content:"",
  publishTime:"",
  imageUrl:"",
  consultantId:1
})
// 刷新
const suaxin=()=>{
  axios.get("/paychologyknoeledge",{
    params:{
      pageNum: currentPage.value,
      pageSize: pageSize.value

    }


  })
      .then((res)=>{
            console.log(res.data.data);
            tableData.value=res.data.data.list;
            total.value=res.data.data.total;
            console.log(res.data.data);



          }
      )
      .catch((err)=>{
        console.log(err);
      })


}



// 加载数据
onMounted(()=>{
  axios.get("/paychologyknoeledge",{
    params:{
      pageNum: currentPage.value,
      pageSize: pageSize.value

    }


  })
      .then((res)=>{
            console.log(res.data.data);
            tableData.value=res.data.data.list;
            total.value=res.data.data.total;
            console.log(res.data.data);



          }
      )
      .catch((err)=>{
        console.log(err);
      })


})

const addBuyCourse1=()=>{
  str1.value="添加";

  dialogFormVisibleAdd.value=true;
}
// 上传文件成功

// 选着文件
const handleFileChange=async (event)=>{
  const file = event.target.files[0];
  if (file) {
    // 检查文件类型是否为 JPEG 或 PNG
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    // 检查文件大小是否小于 2MB
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isJpgOrPng) {
      errorMessage.value = '上传图片只能是 JPG 或 PNG 格式';
      return;
    }
    if (!isLt2M) {
      errorMessage.value = '上传文件大小不能超过 2MB';
      return;
    }
    selectedFile.value = file;
  } else {
    selectedFile.value = null;
  }
  console.log(selectedFile.value);


  event.preventDefault();
  if (!selectedFile.value) {
    errorMessage.value = '请先选择要上传的文件';
    return;
  }
  const formData = new FormData();
  formData.append('file', selectedFile.value);
  try {
    // 发送文件上传请求，将 http://你的后端服务器地址/upload 替换为实际的后端服务地址
    const response = await axios.post('/file', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    });

    uploadedUrl.value = response.data;
    form.value.imageUrl=response.data;
    errorMessage.value = '';
    console.log('文件上传成功，返回的 URL：', response.data);
  }

  catch (error) {
    errorMessage.value = '文件上传失败，错误信息：' + error.message;
    console.error('文件上传失败，错误信息：', error);
  }

}

const  cancle=()=>{
  form.value.content=null;
  form.value.imageUrl="";
  form.value.title="";
  dialogFormVisibleAdd.value= false


}
// 清空
const qingkong=()=>{

  form.value.imageUrl="";
  form.value. content=null;
  form.value.title="";
  uploadedUrl.value="";
  errorMessage.value="";


}
// 确定
const sumbit=()=>{

  axios.post("/paychologyknoeledge",{
    title:form.value.title,
    content:form.value.content,
    imageUrl:form.value.imageUrl,
    consultantId:form.value.consultantId,
  },{
    headers: {"Content-Type": "multipart/form-data"}
  })
      .then((res)=>{
            suaxin();
            console.log(res.data);
          }
      )
      .catch((err)=>{
        alert(err);
      })

  // form.value.assessmentId=null;
  // form.value.image="";
  // form.value.assessmentNum=null;
  // form.value.consultantId=null
  // form.value.title="";
  qingkong();

  dialogFormVisibleAdd.value= false

}
// 删除
const deleteBuyCourse1=(index)=>{
  console.log(index.knowledgeId);
  deleteIndex.value=index.knowledgeId;

  dialogFormVisibleDel.value=true;



}
const deleteBuyCourse2=()=>{
  axios.delete("/paychologyknoeledge/id",{
    params:{
      id:deleteIndex.value

    }


  })
      .then((res)=>{
        console.log(res.data.data);
        suaxin();
        dialogFormVisibleDel.value=false;
      })
      .catch((err)=>{
        console.log(err);
        alert(err);
      })
}
// 修改
const changeBuyCourse1=(index)=>{
  dialogFormVisibleEdit.value=true;
  EditIndex.value=index.knowledgeId;
  console.log( EditIndex.value);
  for (let i=0;i<tableData.value.length;i++){
    if(tableData.value[i].knowledgeId===EditIndex.value){
      form.value.title=tableData.value[i].title;
      // form.value.questions=tableData.value[i].questions;
      form.value.content=tableData.value[i].content;
      break;

    }

  }


}
// 修改取消
const cancle1=()=>{
  dialogFormVisibleEdit.value=false;

}
const handleFileChangeEdit=async (event)=>{
  const file = event.target.files[0];
  if (file) {
    // 检查文件类型是否为 JPEG 或 PNG
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    // 检查文件大小是否小于 2MB
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isJpgOrPng) {
      errorMessage.value = '上传图片只能是 JPG 或 PNG 格式';
      return;
    }
    if (!isLt2M) {
      errorMessage.value = '上传文件大小不能超过 2MB';
      return;
    }
    selectedFile.value = file;
  } else {
    selectedFile.value = null;
  }
  console.log(form.value);
  event.preventDefault();
  if (!selectedFile.value) {
    errorMessage.value = '请先选择要上传的文件';
    return;
  }
  const formData = new FormData();
  formData.append('file', selectedFile.value);
  try {
    // 发送文件上传请求，将 http://你的后端服务器地址/upload 替换为实际的后端服务地址
    const response = await axios.post('/file', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    });

    uploadedUrl.value = response.data;
    form.value.imageUrl=response.data;
    errorMessage.value = '';
    console.log('文件上传成功，返回的 URL：', response.data);
  }

  catch (error) {
    errorMessage.value = '文件上传失败，错误信息：' + error.message;
    console.error('文件上传失败，错误信息：', error);
  }


}
const sumbitEdit=()=>{
  console.log(form.value);

  axios.put("/paychologyknoeledge",{

    knowledgeId:EditIndex.value,
    title:form.value.title,
    content:form.value.content,
    imageUrl:form.value.imageUrl,

  },{
    headers: {"Content-Type": "multipart/form-data"}

  })
      .then((res)=>{
            console.log(res.data);
            suaxin();



          }
      )
      .catch((err)=>{
        console.log(err);
        alert(err);
      })
  qingkong();
  dialogFormVisibleEdit.value=false;



}
const handleSelectionChange=(selection)=>{
  console.log(selection);
  let arr=ref([]);
  for (let i=0;i<selection.length;i++){
    arr.value.push(selection[i].knowledgeId);

  }
  arrayData.value=arr.value;


}
const deketemany1=()=>{


  console.log(arrayData.value);
  axios.delete("/paychologyknoeledge",{
    data: arrayData.value,

  })
      .then((res)=>{
        suaxin();
        console.log(res.data);

      })
      .catch((err)=>{
        console.log(err);
        alert(err);
      })
  dialogFormVisibleDel1.value=false;



}

const deketemany=()=>{
  dialogFormVisibleDel1.value=true;
}
// 搜索
const search=()=>{
  axios.get("/paychologyknoeledge/search",{
    params:{
      title:title.value,
      content:searchContent.value,
    }
  })
      .then((res)=>{
        tableData.value=res.data.data;
        title.value="";
        searchContent.value="";

      })
      .catch((err)=>{
        console.log(err);
        alert(err);
      })

}
const resetSearch=()=>{
  currentPage.value=1;
  suaxin();


}


</script>

<template>

  <div class="top">
    心理知识名称 <el-input v-model="title" style="width: 240px" placeholder="请输入心理知识名称" />
    心理知识内容 <el-input v-model="searchContent" style="width: 240px" placeholder="请输入心理知识内容" />

    <el-button type="primary" style="margin-left: 20px" @click="search" :icon="Search">搜索</el-button>

    <el-button type="warning" style="margin-left: 20px" @click="resetSearch" :icon="Refresh">重置</el-button>
  </div>


  <div class="table">

    <div class="tar">
      <el-button type="primary" plain @click="addBuyCourse1">添加</el-button>
      <el-button type="danger" plain @click="deketemany">批量删除</el-button>
    </div>

    <el-table :data="tableData" @selection-change="handleSelectionChange" style="width: 1280px">
      <el-table-column type="selection" width="55" />
      <el-table-column property="knowledgeId" label="心理知识编号" width="120" />
      <el-table-column property="title" label="心理知识题目"  width="180" />
      <el-table-column property="content" label="内容" width="240" show-overflow-tooltip />
      <el-table-column property="publishTime" label="提交时间" width="180" />
      <el-table-column label="题目图片" width="180" >
        <template #default="scope">
          <img :src="scope.row.imageUrl" alt="题目图片" style="width: 100px; height: auto;" />
        </template>
      </el-table-column>
      <el-table-column property="consultantId" label="发布者id"  />

      <el-table-column property="" label="操作" width="180" >
        <template #default="scope">
          <el-button type="warning" round @click="changeBuyCourse1(scope.row)">修改</el-button>
          <el-button type="danger" round @click="deleteBuyCourse1(scope.row)">删除</el-button>
        </template>

      </el-table-column>
    </el-table>

    <!--    添加购买记录-->
    <el-dialog v-model="dialogFormVisibleAdd" :title="str1" width="500">
      <el-form :model="form">

        <el-form-item label="心理题目" :label-width="formLabelWidth">
          <el-input v-model="form.title" autocomplete="off" />
        </el-form-item>
        <el-form-item label="内容" :label-width="formLabelWidth">
          <el-input v-model="form.content" autocomplete="off"  type="textarea" :rows="3" />
        </el-form-item>
        <el-form-item label="上传图片" :label-width="formLabelWidth">
          <input type="file" id="fileInput" @change="handleFileChange" />
<!--          <button id="uploadButton" @click="shangchuang">上传文件</button>-->

          <div v-if="uploadedUrl">上传成功，URL: {{ uploadedUrl }}</div>
          <div v-if="errorMessage" style="color: red">{{ errorMessage }}</div>
        </el-form-item>



      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancle">取消</el-button>
          <el-button type="primary" @click="sumbit">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>
    <!--    修改-->
    <el-dialog v-model="dialogFormVisibleEdit" :title="str1" width="500">
      <el-form :model="form">

        <el-form-item label="测试题目" :label-width="formLabelWidth">
          <el-input v-model="form.title" autocomplete="off" />
        </el-form-item>
        <el-form-item label="内容" :label-width="formLabelWidth">
          <el-input v-model="form.content" autocomplete="off" type="textarea" :rows="3" />
        </el-form-item>
        <el-form-item label="上传图片" :label-width="formLabelWidth">
          <input type="file" id="fileInput" @change="handleFileChangeEdit" />
          <!--          <button id="uploadButton" @click="shangchuang">上传文件</button>-->
          <div v-if="uploadedUrl">上传成功，URL: {{ uploadedUrl }}</div>
          <div v-if="errorMessage" style="color: red">{{ errorMessage }}</div>
        </el-form-item>



      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancle1">取消</el-button>
          <el-button type="primary" @click="sumbitEdit">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>



    <!---->
    <el-dialog v-model="dialogFormVisibleDel" title="删除信息" width="500" draggable>
      <span>确定要删除该记录吗</span>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisibleDel = false">取消</el-button>
          <el-button type="primary" @click="deleteBuyCourse2">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>
    <!--    多个删除-->
    <el-dialog v-model="dialogFormVisibleDel1" title="删除信息" width="500" draggable>
      <span>确定要删除该记录吗</span>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisibleDel1 = false">取消</el-button>
          <el-button type="primary" @click="deketemany1">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>

    <el-pagination
        :page-size="pageSize"
        :pager-count="7"
        layout="prev, pager, next"
        :total="total"
        @current-change="handleCurrentChange"
    />
  </div>





</template>

<style scoped>
.top{
  padding: 20px 0;
  margin:0 20px;
}

.table{
  padding: 20px 0;
  margin: 0 20px;
}

.tar{
  margin-bottom: 30px;
}

</style>